package com.wqj.ride.happyriding.login.activity

import android.support.v7.app.AppCompatActivity
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo

import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.widget.*
import android.widget.LinearLayout.HORIZONTAL
import com.wqj.ride.happyriding.MainActivity
import com.wqj.ride.happyriding.R

import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * A login screen that offers login via email/password.
 */
class LoginActivity : AppCompatActivity() {
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private var mAuthTask: UserLoginTask? = null
    lateinit var email: AutoCompleteTextView
    lateinit var password: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_login)
        LoginUi().setContentView(this@LoginActivity)
        android.util.Log.d("wqj", "main thread: " + android.os.Process.myTid())
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    // attemptLogin()
                    startActivity(intentFor<MainActivity>("id" to 5).singleTop())
                    return@OnEditorActionListener true
                }
                false
            })
        }
    }

    inner class LoginUi: AnkoComponent<LoginActivity> {
        override fun createView(ui: AnkoContext<LoginActivity>): View {
            return with(ui) {
                verticalLayout {
                    // backgroundColor = ContextCompat.getColor(ui.ctx, android.R.color.white)
                    background = ContextCompat.getDrawable(ui.ctx, R.mipmap.bgmohu)
                    gravity = Gravity.CENTER_HORIZONTAL
                    imageView(R.mipmap.logo1).lparams {
                        width = dip(100)
                        height = dip(100)
                        topMargin = dip(64)
                    }

                    linearLayout {
                        gravity = Gravity.CENTER_VERTICAL
                        orientation = HORIZONTAL
                        // backgroundResource = R.drawable.bg_frame_corner
                        imageView {
                            image = ContextCompat.getDrawable(ui.ctx, R.mipmap.login_pwd)
                        }.lparams(width = dip(20), height = dip(20)) {
                            leftMargin = dip(12)
                            rightMargin = dip(15)
                        }
                        email = autoCompleteTextView {
                            hint = getString(R.string.login_account_hint)
                            hintTextColor = Color.parseColor("#666666")
                            textSize = 14f
                            background = null
                        }.lparams(width = dip(230), height = wrapContent) {
                            topMargin = dip(5)
                        }
                    }.lparams(width = dip(300)) {
                        topMargin = dip(30)
                    }

                    linearLayout {
                        gravity = Gravity.CENTER_VERTICAL
                        orientation = HORIZONTAL
                        // backgroundResource = R.drawable.bg_frame_corner
                        imageView {
                            image = ContextCompat.getDrawable(ui.ctx, R.mipmap.login_pwd)
                        }.lparams(width = dip(20), height = dip(20)) {
                            leftMargin = dip(12)
                            rightMargin = dip(15)
                        }
                        password = editText {
                            hint = getString(R.string.login_password_hint)
                            hintTextColor = Color.parseColor("#666666")
                            textSize = 14f
                            background = null
                        }.lparams {
                            width = dip(230)
                            topMargin = dip(5)
                        }

                    }.lparams {
                        width = dip(300)
                        topMargin = dip(10)
                    }

                    button(R.string.login_btn_text) {
                        gravity = Gravity.CENTER
                        // background = ContextCompat.getDrawable(ui.ctx, R.mipmap.button_red)
                        //textColor = Color.parseColor("#ffffff")
                        textSize = 12f
                        onClick {
                            // attemptLogin()
                            startActivity(intentFor<MainActivity>("id" to 5).singleTop())
                        }
                    }.lparams {
                        width = dip(300)
                        height = dip(45)
                        topMargin = dip(18)
                    }

                    linearLayout {
                        orientation = HORIZONTAL
                        gravity = Gravity.CENTER_VERTICAL
                        checkBox(R.string.login_remember) {
                            textColor = Color.parseColor("#666666")
                            textSize = 16f
                            leftPadding = dip(5)
                        }
                        textView(R.string.login_register) {
                            textColor = Color.parseColor("#1783e3")
                            gravity = Gravity.RIGHT
                            textSize = 16f
                        }.lparams(width = matchParent)
                    }.lparams(width = dip(300)) {
                        topMargin = dip(18)
                    }

                    textView(R.string.login_copyright) {
                        textColor = Color.parseColor("#666666")
                        textSize = 14f
                        gravity = Gravity.CENTER or Gravity.BOTTOM
                    }.lparams {
                        bottomMargin = dip(10)
                        weight = 1f
                    }
                }
            }
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private fun attemptLogin() {
        if (mAuthTask != null) {
            return
        }

        // Reset errors.
        email.error = null
        password.error = null

        // Store values at the time of the login attempt.
        val emailStr = email.text.toString()
        val passwordStr = password.text.toString()

        var cancel = false
        var focusView: View? = null

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(passwordStr) && !isPasswordValid(passwordStr)) {
            password.error = getString(R.string.error_invalid_password)
            focusView = password
            cancel = true
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(emailStr)) {
            email.error = getString(R.string.error_field_required)
            focusView = email
            cancel = true
        } else if (!isEmailValid(emailStr)) {
            email.error = getString(R.string.error_invalid_email)
            focusView = email
            cancel = true
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView?.requestFocus()
        } else {
            mAuthTask = UserLoginTask(emailStr, passwordStr)
            mAuthTask!!.execute(null as Void?)
        }
    }

    private fun isEmailValid(email: String): Boolean {
        //TODO: Replace this with your own logic
        return email.contains("@")
    }

    private fun isPasswordValid(password: String): Boolean {
        //TODO: Replace this with your own logic
        return password.length > 4
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean>() {

        override fun doInBackground(vararg params: Void): Boolean? {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000)
            } catch (e: InterruptedException) {
                return false
            }

            return DUMMY_CREDENTIALS
                    .map { it.split(":") }
                    .firstOrNull { it[0] == mEmail }
                    ?.let {
                        // Account exists, return true if the password matches.
                        it[1] == mPassword
                    }
                    ?: true
        }

        override fun onPostExecute(success: Boolean?) {
            mAuthTask = null

            if (success!!) {
                finish()
            } else {
                password.error = getString(R.string.error_incorrect_password)
                password.requestFocus()
            }
        }

        override fun onCancelled() {
            mAuthTask = null
        }
    }

    companion object {

        /**
         * Id to identity READ_CONTACTS permission request.
         */
        private val REQUEST_READ_CONTACTS = 0

        /**
         * A dummy authentication store containing known user names and passwords.
         * TODO: remove after connecting to a real authentication system.
         */
        private val DUMMY_CREDENTIALS = arrayOf("foo@example.com:hello", "bar@example.com:world")
    }
}
